<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* GMaps Class
*
* Allows to fetch coordinates from GMaps by sending a query url and spliting the data string.
*
*/
class Gmaps {
    
   	var $table_name				= '';
	var $lat_field_name			= '';
	var $lng_field_name			= '';
	var $unidue_id_field_name 	= '';
	var $wrong_address			= '';
	var $correct_address		= '';
	var $run_status				= FALSE;
	var $log_path				= '';
	var $date_fmt				= 'Y-m-d H:i:s';
	var $log_enabled			= FALSE;
	
	/**
	* Constructor
	*
	* @access    public
	* @param    array    initialization parameters
	*/
	function Gmaps($params = array())
	{
		//$CI =& get_instance();		
		if (count($params) > 0)
		{
			$this->initialize($params);        
		}
	
		log_message('debug', "Gmaps Class Initialized");
	}
	
	// --------------------------------------------------------------------
    
    /**
     * Initialize Preferences
     *
     * @access    public
     * @param     array    initialization parameters
     * @return    void
     */
    function initialize($params = array())
    {
        if (count($params) > 0)
        {
            foreach ($params as $key => $val)
            {
                if (isset($this->$key))
                {
                    $this->$key = $val;
                }
            }        
        }
    }
	
	// --------------------------------------------------------------------------
	
	/**
	* Find Latitude Longitude
	*
	* Returns array containing longitude, latitude for an address 
	*
	* @access public
	* @param  string	 
	* @return void
	*/
	//
	function find_lat_lng($search_address='')
	{
		$lng_lat = array();
		
		if(!empty($search_address) && $this->run_status == TRUE)
		{
			$search_url 			= "http://maps.google.com/?q=". urlencode(trim($search_address)) ."&output=kml";
			$contents 				= @file_get_contents($search_url);
			$coordinate_split 		= split("<coordinates>",$contents);
			if(!empty($coordinate_split[1]))
			{
				$slash_coordinate_split = split("</coordinates>",$coordinate_split[1]);
				$quamma_split 			= split(",",$slash_coordinate_split[0]);
				
				$lng_lat[] = $quamma_split[0]; 
				$lng_lat[] = $quamma_split[1];
			}
		}
		
		return $lng_lat;
	}
	
	// --------------------------------------------------------------------------
	
	/**
	* Find all latitude and logitude
	*
	* Finds and updates longitude, latitude for all the records in a table
	*
	* @access public
	* @param  array	 
	* @return void
	*/
	function find_all_lng_lat($address_fields_array = array(),$limit = 0,$offset = 0)
	{	
		$search_address = "";
		
		$address_fields_string = implode("`,`", $address_fields_array);

		$address_fields_string = "`" . $address_fields_string . "`";

		$query = "SELECT " . $this->unidue_id_field_name . " ," . $address_fields_string . 
		 			" FROM " . $this->table_name . 
					" WHERE ( ".
						$this->lat_field_name." = '' OR ". 
						$this->lng_field_name." = '' OR ". 
						$this->lat_field_name." = 'NULL' OR ". 
						$this->lng_field_name." = 'NULL'  ". 
					" ) ".
					" ORDER BY ".$this->unidue_id_field_name .
					" LIMIT ".$limit."
					  OFFSET ".$offset;		
		$CI =& get_instance();
		
		$result = $CI->db->query($query);
		if($result->num_rows > 0)
		{
			foreach($result->result_array() as $record)
			{
				$search_address = "";
				$lng_lat_arr 	= array();
				
				foreach($address_fields_array as $value)
				{
					$search_address .= $record[$value] . ",";
				}
			
				if(!preg_match('/^australia$/i',$search_address))
				{
					//Default the country is set to australia
					$search_address .= "Australia";
				}			
				
				if($search_address)
				{
					$lng_lat_arr = $this->find_lat_lng($search_address);
				}

				if(is_array($lng_lat_arr) && count($lng_lat_arr) > 0)
				{
					$update_query = "REPLACE `".TBL_SITES_LAT_LNG."` 
									 SET `site_id` = '".$record['site_id']."', 
									`latitude` = '".$lng_lat_arr[0]."', 
									`longitude` = '".$lng_lat_arr[1]."'";
					$CI->db->query($update_query);	
					echo '<br/>'.$update_query;		
					
					// Update
					$data = array(							
								$this->lat_field_name => $lng_lat_arr[0],
								$this->lng_field_name => $lng_lat_arr[1]
							);							
					$CI->db->update($this->table_name,$data, array('site_id' => $record['site_id']));
					
					$this->correct_address .= "Latitude and Longitude found for site ID ".
											$record['site_id']." and address : ".$search_address."<br/>\n";					
				}
				else
				{
					$this->wrong_address .= "Latitude and Longitude not found for site ID ".
											$record['site_id']." and address : ".$search_address."<br/>\n";
				}
				
				// Sleep for 1 sec
				sleep(1);				
			}
			// Write a log of sites info where latitude and longitude was not found
			$this->write_log($this->wrong_address);
		}
	}	
	
	// --------------------------------------------------------------------
	
	/**
	 * Write Log File
	 *
	 * Generally this function will be called using the global log_message() function
	 *
	 * @access	public
	 * @param	string	the error message
	 * @return	bool
	 */		
	function write_log($msg)
	{		
		if ($this->log_enabled === FALSE)
		{
			return FALSE;
		}	
			
		$filepath = $this->log_path.'sites-lat-lng-'.date('Y-m-d').EXT;
		$message  = '';
		
		if ( ! file_exists($filepath))
		{
			$message .= "<"."?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?".">\n\n";
		}
					
		if ( ! $fp = @fopen($filepath, FOPEN_WRITE_CREATE))
		{
			return FALSE;
		}
				
		$message .= "\n";
		$message .= date($this->date_fmt)."\n".$msg."\n";
		$message .= repeater('-', 100)."\n";
		
		flock($fp, LOCK_EX);	
		fwrite($fp, $message);
		flock($fp, LOCK_UN);
		fclose($fp);
	
		@chmod($filepath, FILE_WRITE_MODE); 		
		return TRUE;
	}
	
	// --------------------------------------------------------------------------
	
	/**
	 * Get Distance
	 *
	 * Returns straight-line distance between two points on earth
	 *
	 * @access public
	 * @param  string
	 * @param  string
	 * @param  string
	 * @param  string
	 * @param  string	 
	 * @return void
	 */
	function get_distance($lng1, $lat1, $lng2, $lat2, $unit = "K")
	{
		$distance = 0;
		
		$theta = ($lng1 > $lng2)?($lng1 - $lng2):($lng2 - $lng1);
		$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
		$dist = acos($dist);
  		$dist = rad2deg($dist);
		
  		$distance = $dist * 60 * 1.1515;
  		switch(strtoupper($unit))
  		{
	  		default :
			case "K": // Kilometers
				$distance = $distance * 1.609344;
 			break;
  			case "N": // Nautical Miles
   				$distance = $distance * 0.8684;
 			break;
  		}
 		return $distance; 
	}
}
// End of file Gmaps.php 
/* Location: ./system/application/libraries/Gmaps.php */
?>